﻿using System.Reflection.Metadata;
using ModuleBase;
using ModuleBase.googoltech.GTS;
using Newtonsoft.Json;
using System.IO;
using System.Diagnostics;

namespace AxisInit
{
    public class AxisInit : ModuleBase.ModuleBase
    {
        private IAxisCardService _axisCardService;
        private ModuleStateService _moduleStateService;

        public AxisInit(IAxisCardService axisCardService, ModuleStateService moduleStateService)
        {
            _axisCardService = axisCardService;
            _moduleStateService = moduleStateService;
            // 注册模块的 Id
            _moduleStateService.RegisterModule(Id);
            Name = "8轴-固高-初始化";

            CreatePort(PortType.Input, "Input"); // 输出端口 
            CreatePort(PortType.Output, "Output"); // 输出端口 
        }

        public override object Execute(object input)
        {
            if (_moduleStateService.IsStopped)
            {
                return false;
            }
            // 如果模块已经执行成功，则直接返回 true
            if (_moduleStateService.GetModuleExecutionStatus(Id))
            {
                return true;
            }
            AxisParm _axis;
            Status = ModuleBase.ModuleStatus.Executing; // 设置状态为执行中

            try
            {
                List<AxisParm> axisParmList;
                string jsonString = File.ReadAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Top_A8.json"));
                axisParmList = JsonConvert.DeserializeObject<List<AxisParm>>(jsonString);
                _axisCardService.A1 = axisParmList[0];
                _axisCardService.A2 = axisParmList[1];
                _axisCardService.A3 = axisParmList[2];
                _axisCardService.A4 = axisParmList[3];
                _axisCardService.A5 = axisParmList[4];
                _axisCardService.A6 = axisParmList[5];
                _axisCardService.A7 = axisParmList[6];
                _axisCardService.A8 = axisParmList[7];
            }
            catch (Exception ex)
            {
                
                return false;
            }

            bool gtsCardInitResult = _axisCardService.Init(8, "Top_A8", "Top_A8");
            if (!gtsCardInitResult)
            {
                return false;
            }
            Debug.WriteLine("AxisInit");
            // 执行成功，设置模块状态标志为 true
            _moduleStateService.SetModuleExecutionStatus(Id, true);
            return true;
        }

        public override async Task<object> ExecuteAsync(object input)
        {
            var result = await Task.Run(() => Execute(input));
            Output = result;
            return result;
        }

        public override void Initialize()
        {

        }
    }
}
